/*
 * @Author: tcosfish
 * @Date: 2022-07-21 09:24:37
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-07-21 16:18:34
 * @FilePath: \loadFile\src\config\body.config.ts
 */
import { IKoaBodyOptions } from "koa-body"

import path from "path"

import { get_file_ext, is_exists_dir } from "../utils/upload_file_funs"

// TODO 单文件上传已解决, 之后再解决多文件上传的问题
// * https://github.com/postbrid/koa-body-demo
const koa_body: IKoaBodyOptions = {
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, "../../public/uploads"),
    keepExtensions: true,
    maxFieldsSize: 5 * 1024 * 1024,
    onFileBegin: (name, file) => {
      const file_name = file.originalFilename // 文件名
      if (file_name !== null) {
        const ext = get_file_ext(file_name) // 后缀名
        const dir = path.join(__dirname, `../../public/uploads/${ext}`) // 什么后缀名存放在什么文件夹中
        is_exists_dir(dir)
        file.filepath = `${dir}/${file.originalFilename}`
      }
    },
  },
  onError: (error) => {
    console.log(error)
  },
}

export default koa_body
